const express = require('express');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const mysql = require('mysql2');
const https = require('https');
const fs = require('fs');

// 创建 Express 应用
const app = express();

// 创建上传目录
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
  console.log('创建上传目录成功:', uploadDir);
}

// 配置中间件
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 配置 CORS
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

// 请求日志中间件
app.use((req, res, next) => {
  console.log('收到请求:', {
    method: req.method,
    url: req.url,
    headers: req.headers,
    body: req.body,
    query: req.query,
    params: req.params
  });
  next();
});

// 创建数据库连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'root',  // 请根据您的MySQL密码修改
  database: 'travel_diary',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 将连接池转换为 Promise 方式
const promisePool = pool.promise();

// 测试数据库连接
pool.getConnection((err, connection) => {
  if (err) {
    console.error('数据库连接失败:', err);
    return;
  }
  console.log('数据库连接成功');
  connection.release();
});

// 测试数据库连接和表
async function testDatabaseConnection() {
  try {
    // 测试连接
    const connection = await pool.promise().getConnection();
    console.log('数据库连接成功');

    // 检查数据库是否存在
    await connection.query('CREATE DATABASE IF NOT EXISTS travel_diary');
    await connection.query('USE travel_diary');
    console.log('数据库 travel_diary 已就绪');

    // 检查 users 表是否存在
    const [tables] = await connection.query('SHOW TABLES LIKE "users"');
    if (tables.length === 0) {
      console.log('users 表不存在，正在创建...');
      // 创建 users 表
      await connection.query(`
        CREATE TABLE IF NOT EXISTS users (
          id INT PRIMARY KEY AUTO_INCREMENT,
          username VARCHAR(50) NOT NULL UNIQUE,
          password VARCHAR(100) NOT NULL,
          nickname VARCHAR(50),
          avatar_url VARCHAR(255),
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
      `);
      console.log('users 表创建成功');

      // 插入测试数据
      await connection.query(`
        INSERT INTO users (username, password, nickname) VALUES 
        ('admin', '123456', '管理员'),
        ('test', '123456', '测试用户'),
        ('user1', '123456', '用户1')
      `);
      console.log('测试数据插入成功');
    } else {
      console.log('users 表已存在');
      // 检查是否有测试数据
      const [users] = await connection.query('SELECT * FROM users');
      console.log('当前用户数据:', users);
    }

    // 检查 diaries 表是否存在
    const [diaryTables] = await connection.query('SHOW TABLES LIKE "diaries"');
    if (diaryTables.length === 0) {
      console.log('diaries 表不存在，正在创建...');
      // 创建 diaries 表
      await connection.query(`
        CREATE TABLE IF NOT EXISTS diaries (
          id VARCHAR(50) PRIMARY KEY,
          username VARCHAR(50) NOT NULL,
          password VARCHAR(100) NOT NULL,
          title VARCHAR(100) NOT NULL,
          content TEXT NOT NULL,
          location VARCHAR(100),
          images TEXT,
          weather VARCHAR(50),
          mood VARCHAR(50),
          date DATE,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
      `);
      console.log('diaries 表创建成功');
    } else {
      console.log('diaries 表已存在');
    }

    // 检查 spots 表是否存在
    const [spotTables] = await connection.query('SHOW TABLES LIKE "spots"');
    if (spotTables.length === 0) {
      console.log('spots 表不存在，正在创建...');
      // 创建 spots 表
      await connection.query(`
        CREATE TABLE IF NOT EXISTS spots (
          id INT PRIMARY KEY AUTO_INCREMENT,
          name VARCHAR(100) NOT NULL,
          description TEXT,
          image_url VARCHAR(255),
          price DECIMAL(10,2),
          rating DECIMAL(2,1),
          category INT,
          location VARCHAR(100),
          open_time VARCHAR(100),
          suggested_time VARCHAR(50),
          transportation TEXT,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
      `);
      console.log('spots 表创建成功');

      // 插入测试数据
      await connection.query(`
        INSERT INTO spots (name, description, image_url, price, rating, category, location, open_time, suggested_time, transportation) VALUES 
        ('西湖', '杭州西湖，中国十大风景名胜之一，以秀丽的湖光山色和众多的人文古迹闻名于世。', '/images/spots/xihu.jpg', 0, 4.8, 1, '浙江省杭州市西湖区', '全天开放', '3-4小时', '公交：乘坐K7、Y2等多路公交车到西湖站下车。\n地铁：乘坐地铁1号线到龙翔桥站下车，步行约10分钟可到达。'),
        ('故宫', '北京故宫，世界上现存规模最大、保存最为完整的木质结构古建筑之一。', '/images/spots/gugong.jpg', 60, 4.9, 2, '北京市东城区景山前街4号', '8:30-17:00', '4-6小时', '公交：乘坐1、2、52、59、82、99、120等路公交车到故宫站下车。\n地铁：乘坐地铁1号线到天安门东站或天安门西站下车，步行约10-15分钟可到达。'),
        ('黄山', '安徽黄山，以奇松、怪石、云海、温泉"四绝"著称于世。', '/images/spots/huangshan.jpg', 230, 4.7, 1, '安徽省黄山市黄山区汤口镇', '6:30-16:30', '2-3天', '飞机：黄山屯溪国际机场距离黄山风景区约70公里。\n火车：黄山北站（高铁站）距离黄山风景区约40公里。\n汽车：从黄山市区乘坐旅游专线车可直达黄山风景区。')
      `);
      console.log('景点测试数据插入成功');
    } else {
      console.log('spots 表已存在');
      // 检查是否有测试数据
      const [spots] = await connection.query('SELECT * FROM spots');
      console.log('当前景点数据:', spots);
    }

    connection.release();
  } catch (err) {
    console.error('数据库初始化失败:', err);
    throw err;
  }
}

// 调用数据库初始化函数
testDatabaseConnection().catch(err => {
  console.error('数据库初始化失败:', err);
  process.exit(1);
});

// 根路径处理
app.get('/', (req, res) => {
  res.json({
    message: '服务器运行正常',
    endpoints: {
      login: {
        path: '/api/login',
        method: 'POST',
        description: '用户登录接口'
      },
      uploads: '/api/uploads'
    }
  });
});

// 登录接口
app.post('/api/login', async (req, res) => {
  console.log('收到登录请求:', {
    method: req.method,
    url: req.url,
    body: req.body,
    headers: req.headers
  });
  
  const { username, password } = req.body;
  
  // 参数验证
  if (!username || !password) {
    console.log('登录参数验证失败:', { username, password });
    return res.status(400).json({
      success: false,
      message: '账号和密码不能为空'
    });
  }

  try {
    // 先检查用户是否存在
    const [userCheck] = await promisePool.query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );
    console.log('用户检查结果:', userCheck);

    // 查询用户
    const [rows] = await promisePool.query(
      'SELECT * FROM users WHERE username = ? AND password = ?',
      [username, password]
    );

    console.log('数据库查询结果:', rows);
    console.log('SQL查询:', 'SELECT * FROM users WHERE username = ? AND password = ?');
    console.log('查询参数:', [username, password]);

    if (rows.length > 0) {
      // 登录成功
      const user = rows[0];
      res.json({
        success: true,
        message: '登录成功',
        data: {
          id: user.id,
          username: user.username,
          nickName: user.nickname || user.username,
          avatarUrl: user.avatar_url
        }
      });
    } else {
      // 登录失败
      res.status(401).json({
        success: false,
        message: '账号或密码错误'
      });
    }
  } catch (err) {
    console.error('登录查询出错:', err);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 配置图片上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, uniqueSuffix + ext);
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  },
  fileFilter: function (req, file, cb) {
    // 只允许上传图片
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
      return cb(new Error('只允许上传图片文件！'));
    }
    cb(null, true);
  }
});

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 获取日记列表接口
app.get('/api/diaries', async (req, res) => {
  let connection;
  try {
    connection = await promisePool.getConnection();
    console.log('数据库连接成功');
    
    // 从数据库获取日记列表
    const [diaries] = await connection.query(`
      SELECT 
        id,
        username,
        title,
        content,
        location,
        images,
        weather,
        mood,
        date,
        created_at
      FROM diaries 
      ORDER BY created_at DESC
    `);
    console.log('从数据库获取到的日记:', diaries);

    // 处理图片数据
    const formattedDiaries = diaries.map(diary => {
      console.log('处理日记数据:', diary);
      
      let images = [];
      if (diary.images) {
        try {
          // 如果images是字符串，尝试解析JSON
          if (typeof diary.images === 'string') {
            // 检查是否是JSON字符串
            if (diary.images.startsWith('[') || diary.images.startsWith('{')) {
              images = JSON.parse(diary.images);
            } else {
              // 如果不是JSON字符串，可能是单个图片URL
              images = [diary.images];
            }
          } else if (Array.isArray(diary.images)) {
            images = diary.images;
          }
        } catch (e) {
          console.error('解析图片数据失败:', e);
          // 如果解析失败，尝试将整个字符串作为单个图片URL
          images = [diary.images];
        }
      }

      return {
        ...diary,
        images,
        date: diary.date ? diary.date.toISOString().split('T')[0] : null,
        created_at: diary.created_at ? diary.created_at.toISOString() : null
      };
    });

    console.log('格式化后的日记数据:', formattedDiaries);

    res.json({
      success: true,
      data: formattedDiaries
    });
  } catch (err) {
    console.error('获取日记列表失败:', err);
    res.status(500).json({
      success: false,
      error: '获取日记列表失败',
      details: err.message
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
});

// 获取景点列表接口
app.get('/api/spots', async (req, res) => {
  try {
    // 从数据库获取景点数据
    const [spots] = await promisePool.query('SELECT * FROM spots');
    
    res.json({
      success: true,
      data: spots
    });
  } catch (err) {
    console.error('获取景点列表失败:', err);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 创建日记接口
app.post('/api/diaries', upload.array('images', 9), async (req, res) => {
  let connection;
  try {
    connection = await promisePool.getConnection();
    const { title, content, location, weather, mood, date, username, password } = req.body;
    
    // 验证必填字段
    if (!title || !content || !username || !password) {
      return res.status(400).json({
        success: false,
        error: '标题、内容、用户名和密码不能为空'
      });
    }

    const id = Date.now().toString();
    const images = req.files ? req.files.map(file => `/uploads/${file.filename}`) : [];
    
    // 插入日记数据
    await connection.query(
      `INSERT INTO diaries (id, username, password, title, content, location, images, weather, mood, date) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [id, username, password, title, content, location, JSON.stringify(images), weather, mood, date]
    );

    res.json({
      success: true,
      data: {
        id,
        title,
        content,
        location,
        images,
        weather,
        mood,
        date,
        username
      }
    });
  } catch (err) {
    console.error('创建日记失败:', err);
    res.status(500).json({
      success: false,
      error: '创建日记失败'
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
});

// 图片上传接口
app.post('/api/upload', upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        error: '没有上传文件'
      });
    }

    // 返回文件URL
    const fileUrl = `/uploads/${req.file.filename}`;
    console.log('文件上传成功:', fileUrl);
    
    res.json({
      success: true,
      url: fileUrl
    });
  } catch (err) {
    console.error('文件上传失败:', err);
    res.status(500).json({
      success: false,
      error: '文件上传失败'
    });
  }
});

// 404 处理
app.use((req, res) => {
  console.log('404 Not Found:', {
    method: req.method,
    url: req.url,
    body: req.body
  });
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.url,
    method: req.method
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 配置 HTTPS 选项
const httpsOptions = {
  key: fs.readFileSync(path.join(__dirname, 'ssl', 'private.key')),
  cert: fs.readFileSync(path.join(__dirname, 'ssl', 'certificate.crt'))
};

// 创建 HTTPS 服务器
const server = https.createServer(httpsOptions, app);

// 启动服务器
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在 https://localhost:${PORT}`);
}); 